<script lang="ts" setup>
import { ref, unref } from "vue";

import { useVbenModal } from "@vben/common-ui";

import { message } from "ant-design-vue";

import { useVbenForm } from "#/adapter";
import { save, show, update } from "#/api/monitor/crontab";

import { formSchamas } from "./schemas";

const record = ref();
const isUpdate = ref(false);
const gridApi = ref();
const [CrontabForm, formApi] = useVbenForm({
  showDefaultActions: false,
  ...formSchamas,
});
const [Modal, modalApi] = useVbenModal({
  draggable: true,
  onOpenChange(isOpen) {
    isUpdate.value = modalApi.getData()?.isUpdate ?? false;
    record.value = isOpen ? modalApi.getData()?.record || {} : {};
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;

    if (isOpen&&record.value.id) {
        show(record.value?.id).then((data) => {
          formApi.setValues(data);
        });

    } else {
      formApi.setValues(record.value);
    }
  },
  onConfirm() {
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        modalApi.setState({ loading: true, confirmLoading: true });
        const submitApi = unref(isUpdate) ? update : save;
        const apiParams = unref(isUpdate) ? [record.value?.id, values] : [values];
        //@ts-ignore
        submitApi(...apiParams)
          .then(() => {
            message.success("保存成功");
            gridApi.value?.reload();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
  },
});
defineExpose(modalApi);
</script>
<template>
  <Modal :title="isUpdate ? '编辑任务' : '新增任务'" class="w-[50%]">
    <div class="common-form">
      <CrontabForm />
    </div>
  </Modal>
</template>
<style scoped lang="less">
@import "#/assets/styles/common-form.less";
</style>
